<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { ApiResult, baseURL } from "@/util/request";
import { Delete } from "@element-plus/icons-vue";
import { updateQuestion } from "@/api/databaseManage.ts";

interface IDate {
  id: string;
  questionSubject: string;
  questionType: string;
  rightStrQuestionOptions: string;
  optionMiniResponses: [];
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object,
    default: () => {},
  },
  type: {
    type: String,
    default: "1",
  },
});
const token = ref<string>(localStorage.getItem("x-auth-token"));
const questionTypeList = [
  { value: 1, label: "单选题" },
  { value: 2, label: "多选题" },
  { value: 3, label: "判断题" },
];
const emit = defineEmits(["update:visible", "update:data", "submit"]);
const uploadRef = ref();
const ruleFormRef = ref();
const submitLoading = ref<boolean>(false);

const formData = ref<IDate>({
  id: "",
  questionSubject: "",
  questionType: "",
  rightStrQuestionOptions: "",
  optionMiniResponses: [],
});
const optionMiniResponsesCopy = ref<any>([]);

const rules = reactive<FormRules<IDate>>({
  questionSubject: [{ required: true, message: "请输入", trigger: "blur" }],
  rightStrQuestionOptions: [
    { required: true, message: "请选择", trigger: "change" },
  ],
});

const dialogVisible = computed({
  get() {
    return props.visible;
  },

  set(visible: boolean) {
    emit("update:visible", visible);
  },
});

function closeDialog() {
  resetForm(ruleFormRef.value);
  emit("update:visible", false);
  emit("update:data", null);
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    let result: ApiResult<any>;
    if (valid) {
      submitLoading.value = true;
      result = await updateQuestion(formData.value);
      const { success, msg } = result;
      submitLoading.value = false;
      if (!success) {
        ElMessage.error(msg);
        return;
      }
      ElMessage.success("操作成功");
      closeDialog();
      emit("submit");
    } else {
      console.log("error submit!", fields);
    }
  });
};

function changeRadioGroup() {
  if (formData.value.questionType == "3") {
    formData.value.optionMiniResponses = [
      {
        questionOption: "A",
        optionContent: "对",
        optionType: "1",
        isRight: false,
      },
      {
        questionOption: "B",
        optionContent: "错",
        optionType: "1",
        isRight: false,
      },
    ];
    formData.value.rightStrQuestionOptions = "";
  } else {
    formData.value.optionMiniResponses = JSON.parse(
      optionMiniResponsesCopy.value,
    );
  }
}

function del(index: any) {
  formData.value.optionMiniResponses.splice(index, 1);
  let a = "";
  formData.value.optionMiniResponses.forEach((item: any, i: any) => {
    if (item.isRight) {
      a += String.fromCharCode(64 + i + 1);
    }
  });
  formData.value.rightStrQuestionOptions = a;
}

function clearUploadFile() {
  uploadRef.value?.clearFiles();
}

function onUploadSuccess(response: any, index: any) {
  if (response?.code != 200) {
    ElMessage.error(response?.msg || "上传错误！");
    clearUploadFile();
    return;
  }
  formData.value.optionMiniResponses[index].optionContent =
    response?.data?.fileUrl;
  ElMessage.success("上传完成！");
}

function getCheckbox(val: boolean, index: any) {
  let a = "";
  formData.value.optionMiniResponses.forEach((item: any, i: any) => {
    if (formData.value.questionType != "2" && val) {
      if (index == i) {
        item.isRight = true;
      } else {
        item.isRight = false;
      }
    }
    if (item.isRight) {
      a += String.fromCharCode(64 + i + 1);
    }
  });
  formData.value.rightStrQuestionOptions = a;
}

function confirmEvent() {
  formData.value.optionMiniResponses.push({
    isRight: false,
    optionContent: "",
    optionType: "1",
    questionOption: "",
  });
}
function cancelEvent() {
  formData.value.optionMiniResponses.push({
    isRight: false,
    optionContent: "",
    optionType: "2",
    questionOption: "",
  });
}

watch(dialogVisible, (visible) => {
  Object.keys(formData.value).forEach((key: any) => {
    optionMiniResponsesCopy.value = visible
      ? JSON.stringify(props.data.optionMiniResponses)
      : "";
    formData.value[key as keyof IDate] = visible ? props.data?.[key] || "" : "";
  });
});
</script>

<template>
  <el-dialog
    @close="closeDialog"
    v-model="dialogVisible"
    :title="`编辑`"
    width="50%"
  >
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="题型:" prop="questionType">
        <el-radio-group
          v-model="formData.questionType"
          @change="changeRadioGroup"
        >
          <div></div>
          <el-radio
            v-for="item in questionTypeList"
            :key="item.value"
            :value="item.value"
            :label="item.value"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="题目:" prop="questionSubject">
        <el-input
          style="width: 100%"
          v-model="formData.questionSubject"
          :autosize="{ minRows: 3, maxRows: 4 }"
          type="textarea"
        />
      </el-form-item>
      <el-form-item label="选项:" prop="optionMiniResponses">
        <div style="display: flex">
          <div style="width: 480px">
            <div
              style="margin: 3px 0 3px 15px; height: auto"
              v-for="(item, index) in formData.optionMiniResponses"
              :key="index + 'a'"
            >
              <div style="width: 480px; display: flex">
                <el-checkbox
                  v-model="item.isRight"
                  true-value="1"
                  false-value="2"
                  @change="(val: boolean) => getCheckbox(val, index)"
                ></el-checkbox>
                <el-input
                  v-if="item.optionType == 1"
                  style="width: 80%; margin: 0 10px"
                  v-model="item.optionContent"
                  type="text"
                >
                  <template #prepend>{{
                    String.fromCharCode(64 + index + 1)
                  }}</template>
                </el-input>
                <div v-if="item.optionType == 2" style="margin: auto 10px">
                  {{ String.fromCharCode(64 + index + 1) + "、" }}
                </div>
                <el-upload
                  v-if="item.optionType == 2"
                  ref="uploadRef"
                  class="avatar-uploader"
                  :headers="{ 'x-auth-token': token }"
                  :show-file-list="false"
                  :action="`${baseURL}manage/v1/storage/upload?dir=videoDir`"
                  :on-success="(val: any) => onUploadSuccess(val, index)"
                >
                  <el-image
                    v-if="item.optionContent"
                    style="width: 60px; height: 60px"
                    :src="baseURL + item.optionContent"
                  />
                  <el-icon v-else class="avatar-uploader-icon"
                    ><Plus
                  /></el-icon>
                </el-upload>
                <el-button
                  :icon="Delete"
                  circle
                  class="input_btn"
                  @click="del(index)"
                />
              </div>
            </div>
          </div>
          <div style="margin-left: 10px">
            <el-popconfirm
              width="220"
              confirm-button-text="文本"
              cancel-button-text="图片"
              icon-color="#626AEF"
              title="请选择添加选项的类型"
              @confirm="confirmEvent"
              @cancel="cancelEvent"
            >
              <template #reference>
                <el-button>添加一个选项</el-button>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="答案:" prop="rightStrQuestionOptions">
        {{ formData.rightStrQuestionOptions }}
      </el-form-item>
    </el-form>
    <div class="footer">
      <el-button
        @click="submitForm(ruleFormRef)"
        type="primary"
        :loading="submitLoading"
      >
        保存
      </el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.footer {
  width: 100%;
  text-align: center;
  margin-top: 50px;
}
.optionMiniResponses {
  width: 100%;
  display: flex;
  margin: 5px 0;
  .input_btn {
    margin-left: 10px;
  }
}
.avatar-uploader {
  margin: 0 50px 0px 10px;
}
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #999;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: #999;
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
}
:deep(.w-e-text-container) {
  min-height: 200px;
  width: 100%;
}
</style>
